package com.Hiram.Store;

import com.Hiram.bean.ChatMessages;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.glassfish.jaxb.core.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component
public class MongodbChatMemoryStore implements ChatMemoryStore {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        Integer userId = getCurrentUserId();
        Criteria criteria = Criteria.where("memoryId").is(memoryId).and("userId").is(userId);
        Query query = new Query(criteria);
        ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);

        if (chatMessages == null) return new LinkedList<>();
        String content = chatMessages.getContent();
        return ChatMessageDeserializer.messagesFromJson(content);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        Integer userId = getCurrentUserId();
        Criteria criteria = Criteria.where("memoryId").is(memoryId).and("userId").is(userId);
        Query query = new Query(criteria);

        Update update = new Update();
        update.set("content", ChatMessageSerializer.messagesToJson(messages));
        // 修改或新增
        mongoTemplate.upsert(query, update, ChatMessages.class);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        Integer userId = getCurrentUserId();
        Criteria criteria = Criteria.where("memoryId").is(memoryId).and("userId").is(userId);
        Query query = new Query(criteria);
        mongoTemplate.remove(query, ChatMessages.class);
    }

    private Integer getCurrentUserId() {
//        TODO 通过ThreadLocalUtil来获取用户id
//        Map<String, Object> map = ThreadLocalUtil.get();
//        return (Integer) map.get("id");
        return 1;
    }
}